package br.ucb.cm.main.mainview;

import br.ucb.cm.board.util.BoardUtil;
import br.ucb.cm.config.GameInstance;
import br.ucb.cm.config.bean.NewGameConfig;
import br.ucb.cm.config.bean.PieceConfig;
import br.ucb.cm.main.common.GeneralConstants.PlayerEnum;
import br.ucb.cm.main.common.GeneralConstants.PlayerTypeEnum;
import br.ucb.cm.main.mainview.ui.IfcNewGame;
import br.ucb.cm.main.mainview.ui.NewGameUI;

public class NewGame implements IfcNewGame{
	private NewGameUI ui;
	private NewGameConfig config;
	private boolean configLoaded;
	
	public NewGame() {
		this.configLoaded = false;
		this.ui = new NewGameUI(this);
	}

	@Override
	public PieceConfig doAction(ActionEnum action) {
		switch (action) {
		case GET_STD_PIECE:
			return GameInstance.getInstance().getConfig().getPieces().get(0);
		case GET_ENEMY_PIECE:
			return BoardUtil.getEnemyPiece(GameInstance.getInstance().getConfig().getPieces().get(0));
		case CANCEL:
			setConfigLoaded(false);
		default:
			return null;
		}
	}
	
	@Override
	public void doAction(ActionEnum action, String player1Name, String player2Name,
			int difficulty, PlayerTypeEnum p1Type, PlayerTypeEnum p2Type,
			PlayerEnum startingPlayer) {
		switch (action) {
		case SET_CONFIG:
			PlayerEnum.PLAYER_ONE.setPlayerType(p1Type);
			PlayerEnum.PLAYER_TWO.setPlayerType(p2Type);
			
			if(player1Name != null && !player1Name.trim().isEmpty())
				PlayerEnum.PLAYER_ONE.setName(player1Name);
			else
				PlayerEnum.PLAYER_ONE.setName(p1Type == PlayerTypeEnum.CPU ? "CPU 1" : "Jogador 1");
			
			if(player2Name != null && !player2Name.trim().isEmpty())
				PlayerEnum.PLAYER_TWO.setName(player2Name);
			else
				PlayerEnum.PLAYER_TWO.setName(p2Type == PlayerTypeEnum.CPU ? "CPU 2" : "Jogador 2");
			
			config = new NewGameConfig(
					difficulty, 
					startingPlayer
			);
			
			GameInstance.getInstance().loadNewGameConfig(config);
			setConfigLoaded(true);
			
			setUi(null);
			break;
		default:
			break;
		}
	}
	
	public boolean isConfigLoaded() {
		return configLoaded;
	}

	public void setConfigLoaded(boolean configLoaded) {
		this.configLoaded = configLoaded;
	}

	public NewGameConfig getConfig() {
		return config;
	}

	public void setConfig(NewGameConfig config) {
		this.config = config;
	}

	public NewGameUI getUi() {
		if(this.ui == null)
			this.ui = new NewGameUI(this);
		return ui;
	}
	
	public void setUi(NewGameUI ui) {
		this.ui = ui;
	}

	public void show() {
		getUi().setVisible(true);
	}

}